package com.xkstream.client.ui.live;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver;
import com.netease.nimlib.sdk.chatroom.constant.MemberType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomKickOutEvent;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.xkstream.client.R;
import com.xkstream.client.ZegoApiManager;
import com.xkstream.client.application.Application;
import com.xkstream.client.api.API;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.AnchorInfo;
import com.xkstream.client.entity.BetRank;
import com.xkstream.client.entity.Game;
import com.xkstream.client.entity.kt.GiftRankingData;
import com.xkstream.client.lgim.LgMessage;
import com.xkstream.client.nim.BetRankAndNumAttachment;
import com.xkstream.client.entity.GamblingPartyResult;
import com.xkstream.client.nim.GifAttachment;
import com.xkstream.client.entity.ReceiveGift;
import com.xkstream.client.nim.NimHelper;
import com.xkstream.client.nim.ResultAttachment;
import com.xkstream.client.nim.RobotAttachment;
import com.xkstream.client.entity.User;
import com.xkstream.client.nim.WinAttachment;
import com.xkstream.client.faceunity.EffectAndFilterSelectAdapter;
import com.xkstream.client.presenter.LiveRoomContract;
import com.xkstream.client.presenter.LiveRoomPresenter;
import com.xkstream.client.ui.adapter.BetonRankAdapter;
import com.xkstream.client.ui.adapter.ReceiveGiftRankAdapter;
import com.xkstream.client.ui.adapter.TodayGiftRankAdapter;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.entity.Gift;

import com.xkstream.client.ui.adapter.ChatRoomAdapter;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.L;
import com.xkstream.client.utils.ListViewUtil;
import com.xkstream.client.utils.LogFileUtil;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.NetUtil;
import com.xkstream.client.utils.PreferenceUtils;
import com.xkstream.client.view.gift.GiftShowManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;

import com.zego.zegoliveroom.callback.IZegoLiveEventCallback;
import com.zego.zegoliveroom.callback.IZegoLivePublisherCallback;
import com.zego.zegoliveroom.callback.IZegoLoginCompletionCallback;
import com.zego.zegoliveroom.callback.IZegoRoomCallback;
import com.zego.zegoliveroom.constants.ZegoBeauty;
import com.zego.zegoliveroom.constants.ZegoConstants;
import com.zego.zegoliveroom.constants.ZegoVideoViewMode;
import com.zego.zegoliveroom.entity.AuxData;
import com.zego.zegoliveroom.entity.ZegoStreamInfo;
import com.zego.zegoliveroom.entity.ZegoStreamQuality;

import static com.xkstream.client.application.Application.mZegoLiveRoom;


/**
 * Created by admin on 2017/3/9.
 */

public class LiveRoomActivity extends BaseActivity<LiveRoomContract.Presenter>
        implements ChatRoomAdapter.CommentOnClickListener, LiveRoomContract.View {
    @BindView(R.id.llContent)
    RelativeLayout llContent;
    @BindView(R.id.btnCameraTurn)
    TextView btnCameraTurn;
    @BindView(R.id.rlAnchorInfo)
    RelativeLayout rlAnchorInfo;
    @BindView(R.id.lvComment)
    ListView lvComment;
    @BindView(R.id.btnGiftRank)
    TextView btnGiftRank;
    @BindView(R.id.ivClose)
    ImageView ivClose;
    @BindView(R.id.llBetonRank)
    LinearLayout llBetonRank;
    @BindView(R.id.llGiftHistory)
    LinearLayout llGiftHistory;
    @BindView(R.id.llGiftContent)
    LinearLayout llGiftContent;
    @BindView(R.id.lvBetonRank)
    ListView lvBetonRank;
    @BindView(R.id.llResult)
    LinearLayout llResult;
    @BindView(R.id.llHandle)
    LinearLayout llHandle;
    @BindView(R.id.ivHeader)
    ImageView ivHeader;
    @BindView(R.id.tvAnchorName)
    TextView tvAnchorName;
    @BindView(R.id.tvFuSuitPatterns)
    TextView tvFuSuitPatterns;
    @BindView(R.id.tvLuSuitPatterns)
    TextView tvLuSuitPatterns;
    @BindView(R.id.tvShouSuitPatterns)
    TextView tvShouSuitPatterns;
    @BindView(R.id.tvZhuangSuitPatterns)
    TextView tvZhuangSuitPatterns;
    @BindView(R.id.ivFuResult)
    ImageView ivFuResult;
    @BindView(R.id.ivLuResult)
    ImageView ivLuResult;
    @BindView(R.id.ivShuResult)
    ImageView ivShouResult;
    @BindView(R.id.tvOnlineNum)
    TextView tvOnlineNum;

    //百家乐控件
    @BindView(R.id.tvBJLZhuangDuiResult)
    TextView tvBJLZhuangDuiResult;
    @BindView(R.id.ivBJLZhuangDuiResult)
    ImageView ivBJLZhuangDuiResult;
    @BindView(R.id.tvBJLZhuangResult)
    TextView tvBJLZhuangResult;
    @BindView(R.id.ivBJLZhuangResult)
    ImageView ivBJLZhuangResult;
    @BindView(R.id.tvBJLHeResult)
    TextView tvBJLHeResult;
    @BindView(R.id.ivBJLHeResult)
    ImageView ivBJLHeResult;
    @BindView(R.id.tvBJLXianResult)
    TextView tvBJLXianResult;
    @BindView(R.id.ivBJLXianResult)
    ImageView ivBJLXianResult;
    @BindView(R.id.tvBJLXianDuiResult)
    TextView tvBJLXianDuiResult;
    @BindView(R.id.ivBJLXianDuiResult)
    ImageView ivBJLXianDuiResult;

    //龙虎出控件
    @BindView(R.id.tvLongResult)
    TextView tvLongResult;
    @BindView(R.id.ivLongResult)
    ImageView ivLongResult;
    @BindView(R.id.tvHeResult)
    TextView tvHeResult;
    @BindView(R.id.ivHeResult)
    ImageView ivHeResult;
    @BindView(R.id.tvHuResult)
    TextView tvHuResult;
    @BindView(R.id.ivHuResult)
    ImageView ivHuResult;

    @BindView(R.id.llDezhou)
    LinearLayout llDezhou;
    @BindView(R.id.llBaijiale)
    LinearLayout llBaijiale;
    @BindView(R.id.llLonghuchu)
    LinearLayout llLonghuchu;
    @BindView(R.id.texture)
    TextureView textureView;
    @BindString(R.string.alert_exit)
    String exitEdit;

    private Vibrator mVibrator;

    private long startTime;

    private boolean isPublishing = false;

    GiftShowManager giftShowManager;


    private Context context;


    private boolean isFront = true;

    public ChatRoomAdapter adapter;

    public List<Object> chatRoomMessages = new ArrayList<>();


    private LiveWebSocket webSocket;
    private OkHttpClient client;
    private Request request;

    private String roomId;

    private HashMap<String, String> params = new HashMap<>();
    private Dialog commentDialog;

    private List<BetRank> ranks = new ArrayList<>();
    private BetonRankAdapter betOnRankAdapter;

    private List<ReceiveGift> total = new ArrayList<>();

    private List<ReceiveGift> receiveGiftlist = new ArrayList<>();

    private List<ReceiveGift> day = new ArrayList<>();

    private List<ReceiveGift> week = new ArrayList<>();

    private List<ReceiveGift> month = new ArrayList<>();

    //人脸识别需要传的参数
    int[] m_items = new int[3];

    boolean m_is_sw_encoding = true;

    int m_cur_texid = -1;

    //pause
    private static boolean mFuNotifyPause;
    //当前展示的人脸识别动画
    int m_created_item_id = -1;
    //需要替换的人脸识别动画
    int m_cur_item_id = -1;


    int m_frame_id = 0;

    byte[] m_cur_image = null;

    static final String[] m_item_names = {"huahuan.mp3", "leisi.mp3", "birth.mp3", "FU_tunvlang_2D.mp3", "xiangsumojing.mp3", "FU_xiaochou_2D_ARMesh.mp3", "qinqin.mp3", "qiubite.mp3"};
    //游戏类型
    private String gameType;

    private LinkedBlockingQueue<Gift> queue = new LinkedBlockingQueue<>();

    private Queue<GifAttachment> tietuGift = new LinkedBlockingQueue<>();

    private ReceiveGiftRankAdapter receiveGiftRankAdapter;

    int m_tracking;

    boolean isRanking;


    boolean fontCam = true;

    private boolean liveClosed = false;


    private void loadDaoju() {
//        try {
//        InputStream is = context.getAssets().open("YelloEar.mp3");
//        byte[] item_data = new byte[is.available()];
//        is.read(item_data);
//        is.close();
//            int[] m_items[0] = faceunity.fuCreateItemFromPackage(item_data);
//    } catch (IOException e) {
//        e.printStackTrace();
//    }

    }

    private static final int CODE_RECONNECT = 0X3001;
    private static final int CODE_SENDHEARTBEAT = 0X4001;
    private static final int CODE_QUERYSTATUS = 0X5001;
    private boolean sendResult;

    NetworkReceiver receiver;
    boolean needRepaire = false;
    private String selectedFace = "none";

    private Disposable disposable;


    @Override
    protected void initViews(Bundle savedInstanceState) {
        // Decide FULL screen or real size
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_live);
        ButterKnife.bind(this);
        presenter = new LiveRoomPresenter(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        context = this;
//        llAnchorInfo.getBackground().setAlpha(40);
//        llAdminList.getBackground().setAlpha(40);

        gameType = getIntent().getStringExtra("gameType");
        initGameZone();

        User user = Application.getUser();
        roomId = user.getAnchor().getNeteaseChatRoomId();
        initYX(roomId);
        //initVideoConfiguration();
        //   prepareLive();
        initView();
        mVibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
        //   sendGift();
//        giftHandler.sendEmptyMessage(0);
        registerNetworkBrocastRecevier();
        tvOnlineNum.setText("1");
    }

    private void initGameZone() {
        if (gameType.equals("1")) {
            llDezhou.setVisibility(View.VISIBLE);
        } else if (gameType.equals("2")) {
            llDezhou.setVisibility(View.VISIBLE);
        } else if (gameType.equals("3")) {
            llLonghuchu.setVisibility(View.VISIBLE);
        } else if (gameType.equals("4")) {
            llBaijiale.setVisibility(View.VISIBLE);
        } else if (gameType.equals("5")) {
            llResult.setVisibility(View.INVISIBLE);
        }
    }


    private void registerNetworkBrocastRecevier() {
        receiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }

    private int recoonCount;
    private int badNetwork;
    private int badNetworkSeconds;

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_RECONNECT:
                    connectWebSocket();
                    LogUtil.e(TAG, "connect count " + recoonCount);
                    if (recoonCount >= 5) {
                        recoonCount = 0;
                        LogFileUtil.getDefault().put(TAG, String.format("connectWebSocket faild 5,exit liveroom"));
                        finishWithNoWebSocket();
                        removeMessages(CODE_RECONNECT);
                    }
                    recoonCount++;
                    break;
                case CODE_SENDHEARTBEAT:
                    removeMessages(CODE_SENDHEARTBEAT);
                    sendResult = webSocket.sendMessage("send heart beat from anchor");
                    LogUtil.e(TAG, "sendResult " + sendResult);
                    if (!sendResult) {
                        removeMessages(CODE_SENDHEARTBEAT);
                        release();
                    } else {
                        sendEmptyMessageDelayed(CODE_SENDHEARTBEAT, 25 * 1000);
                    }
                    break;
                case CODE_QUERYSTATUS:
                    removeMessages(CODE_QUERYSTATUS);
                    if (sendResult) {
                        getAnchorDetail();
                    }
                    break;

            }
        }
    };

    private void finishWithNoWebSocket() {
        runOnUiThread(() -> {
            liveClosed = true;
            NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
            showExitDialog("socket通信失败，请退出程序后重试");
            LogUtil.e(TAG, "socket通信失败，请退出程序后重试");
            LogFileUtil.getDefault().put(TAG, String.format("socket通信失败，请退出程序后重试"));
            anchorOff();
            release();
        });
    }

    /*Handler giftHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (tietuGift.size() > 0) {
                selectTietu();
                giftHandler.sendEmptyMessageDelayed(0, 5000);
            } else {
                if (ZegoApiManager.getInstance().getFaceunityController() != null) {
                    ZegoApiManager.getInstance().getFaceunityController().
                            onEffectItemSelected(EffectAndFilterSelectAdapter.EFFECTNAMEMAP
                                    .get("none"));
                    selectedFace = "none";
                }
                giftHandler.sendEmptyMessageDelayed(0, 5000);
            }
        }
    };*/


    //设置推流
    private void prepareLive() {
        if (isPublishing) {
            return;
        } else {
            mZegoLiveRoom.setPreviewView(textureView);
            mZegoLiveRoom.startPreview();
            mZegoLiveRoom.enableBeautifying(ZegoBeauty.POLISH | ZegoBeauty.WHITEN);
            /*mZegoLiveRoom.setSharpenFactor(2);
            mZegoLiveRoom.setWhitenFactor(0.1f);
            mZegoLiveRoom.setSharpenFactor(0.6f);
            mZegoLiveRoom.setPolishStep(4);*/
            mZegoLiveRoom.enableCaptureMirror(true);
            mZegoLiveRoom.enablePreviewMirror(false);
            mZegoLiveRoom.setPreviewViewMode(ZegoVideoViewMode.ScaleAspectFill);
            mZegoLiveRoom.setZegoRoomCallback(new IZegoRoomCallback() {
                @Override
                public void onKickOut(int i, String s) {
                    Log.e(TAG, String.format("onKickOut code %d  msg:%s", i, s));
                    anchorOff();
                    release();
                    liveClosed = true;
                    NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
                    AppManager.getAppManager().finishActivity();
                    Bitmap bitmap = textureView.getBitmap(DeviceUtils.dp2px(context, 360 / 3),
                            DeviceUtils.dp2px(context, 640 / 3));
                    Intent intent = new Intent(LiveRoomActivity.this, LiveEndActivity.class);
                    LiveHelper.bitmap = bitmap;
                    LogFileUtil.getDefault().put(TAG, String.format("onKickOut code %d  msg:%s", i, s));
                    intent.putExtra("starttime", startTime);
                    showToast(R.string.kickout);
//                    startActivity(intent);
                    showExitDialog(getResources().getString(R.string.kickout));

                }

                @Override
                public void onDisconnect(int i, String s) {
                    release();
                    needRepaire = true;
                    Log.e(TAG, String.format("onDisconnect code %d  msg:%s", i, s));
                    LogFileUtil.getDefault().put(TAG + String.format(" onDisconnect code %d  msg:%s", i, s));
//                    showToast(R.string.reconnecting);
                    User user = Application.getUser();
                    showExitDialog(getResources().getString(R.string.disconnect));
                    /*mZegoLiveRoom.startPublishing(user.getAnchor().getAnchor_push_ur(), "android_" + user.getExt_info().getNickname(), ZegoConstants.PublishFlag.JoinPublish);
                    connectWebSocket();
                    isPublishing = false;*/
                    LogFileUtil.getDefault().put(TAG, String.format("onDisconnect code %d  msg:%s", i, s));
                }

                @Override
                public void onReconnect(int i, String s) {

                }

                @Override
                public void onTempBroken(int i, String s) {

                }

                @Override
                public void onStreamUpdated(int i, ZegoStreamInfo[] zegoStreamInfos, String s) {

                }

                @Override
                public void onStreamExtraInfoUpdated(ZegoStreamInfo[] zegoStreamInfos, String s) {

                }

                @Override
                public void onRecvCustomCommand(String s, String s1, String s2, String s3) {

                }
            });
            final User user = Application.getUser();
            boolean loginResult = mZegoLiveRoom.loginRoom("roomId:" + user.getAnchor().getRoom_id_pk(), ZegoConstants.RoomRole.Anchor, new IZegoLoginCompletionCallback() {
                @Override
                public void onLoginCompletion(int i, ZegoStreamInfo[] zegoStreamInfos) {
                    if (i == 0) {
                        Log.e(TAG, "login success " + i);
                        // 登录成功
                        // 调用startPublish开始直播，flag是直播属性
                        mZegoLiveRoom.startPublishing(user.getAnchor().getAnchor_push_ur(), "test", ZegoConstants.PublishFlag.JoinPublish);
                        connectWebSocket();
                        startTime = System.currentTimeMillis();
                    } else {
                        // 登录失败, 业务侧打印日志
                        Log.e(TAG, "login failed " + i);
                        anchorOff();
                        NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
                        showExitDialog("登录直播房间失败，请退出后重试");
                        LogFileUtil.getDefault().put(TAG, String.format("zego login Faild code %d  ", i));
                    }
                }
            });

            if (!loginResult) {
                showExitDialog(getString(R.string.login_zego_failed));
            }

            mZegoLiveRoom.setZegoLiveEventCallback(new IZegoLiveEventCallback() {
                @Override
                public void onLiveEvent(int i, HashMap<String, String> hashMap) {
                    Log.e(TAG, String.format("onLiveEvent  code %d", i));
                    StringBuilder sb = new StringBuilder("onLiveEvent  msg : ");
                    for (String key : hashMap.keySet()) {
                        sb.append(key).append(" : ").append(hashMap.get(sb)).append("\n");
                    }
                    Log.e(TAG, sb.toString());
                }
            });
            mZegoLiveRoom.setZegoLivePublisherCallback(new IZegoLivePublisherCallback() {
                @Override
                public void onPublishStateUpdate(int i, String s, HashMap<String, Object> hashMap) {
                    Log.e(TAG, String.format("onPublishStateUpdate code : %d\n msg : %s", i, s));
                    if (i > 0) {
                        anchorOff();
                        release();
                        liveClosed = true;
                        NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
                        AppManager.getAppManager().finishActivity();
                        LogUtil.e(TAG, "onPublishStateUpdate 流断开");
                    }
                }

                @Override
                public void onJoinLiveRequest(int i, String s, String s1, String s2) {
                    Log.e(TAG, String.format("onJoinLiveRequest s1 : %s  s2 : ", s1, s2));
                }

                @Override
                public void onPublishQualityUpdate(String s, ZegoStreamQuality zegoStreamQuality) {
                    LogUtil.e(TAG, String.format("onPublishQualityUpdate : %s  s2 : ", s));
                    LogUtil.e(TAG, String.format("Quality:%s VideoBitrate:%s VideoFPS:%s", zegoStreamQuality.quality,
                            zegoStreamQuality.videoBitrate, zegoStreamQuality.videoFPS));
                    if (zegoStreamQuality.quality == 3) {
                        /*if (inTimeZone(Calendar.getInstance().get(Calendar.SECOND) - badNetworkSeconds, 3)) {
                            badNetwork++;
                        } else {
                            badNetwork = 0;
                        }
                        badNetworkSeconds = Calendar.getInstance().get(Calendar.SECOND);*/
                        badNetwork++;
                        if (badNetwork >= 15) {
                            badNetwork = 0;
                            showBadNetWorkDialog();
                        }
                    }
                }

                @Override
                public AuxData onAuxCallback(int i) {
                    return null;
                }

                @Override
                public void onCaptureVideoSizeChangedTo(int i, int i1) {

                }

                @Override
                public void onMixStreamConfigUpdate(int i, String s, HashMap<String, Object> hashMap) {

                }
            });
            LogUtil.e(TAG, String.format("push sound level : %f ", mZegoLiveRoom.getCaptureSoundLevel()));
            isPublishing = true;
        }
    }

    private boolean inTimeZone(int dt, int value) {
        return (dt >= 0 && dt < value) ||
                (dt < 0 && (dt + 60) < value);
    }

    private void loadGiftRank() {
        User user = Application.getUser();
        String id = user.getUser_code();
        presenter.getGiftRank(id);
        isRanking = true;
    }


    private void initView() {
        llBetonRank.getBackground().setAlpha(110);
        llGiftHistory.getBackground().setAlpha(110);
        rlAnchorInfo.getBackground().setAlpha(180);
        adapter = new ChatRoomAdapter(chatRoomMessages, total, context, this);
        lvComment.setAdapter(adapter);
        lvComment.setOnItemClickListener(null);
        betOnRankAdapter = new BetonRankAdapter(context, ranks);
        lvBetonRank.setAdapter(betOnRankAdapter);
        giftShowManager = new GiftShowManager(context, llGiftContent);
        giftShowManager.showGift();
        User user = Application.getUser();
        tvAnchorName.setText(user.getExt_info().getNickname());
        AsyncImage.loadPhoto(context, user.getExt_info().getHead_icon(), ivHeader);
    }

    private void initYX(String roomId) {
        EnterChatRoomData data = new EnterChatRoomData(roomId);
        User user = Application.getUser();
        String nickName = user.getExt_info().getNickname();
        data.setNick(nickName);
        NIMClient.getService(ChatRoomService.class).enterChatRoom(data).setCallback(new RequestCallback() {
            @Override
            public void onSuccess(Object o) {
                initChatRoom();
            }

            @Override
            public void onFailed(int i) {
                chatRoomMessages.add("系统消息：进入聊天室失败，请杀掉应用进程重新登录");
                adapter.notifyDataSetChanged();
                LogFileUtil.getDefault().put(TAG, String.format("nim enter chatroom Faild code %d  ", i));
            }

            @Override
            public void onException(Throwable throwable) {
                showToast(throwable.toString());
            }
        });

        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode>() {
                    public void onEvent(StatusCode status) {
                        switch (status) {
                            case KICKOUT:
                                chatRoomMessages.add("系统消息：您的账号在别处登录，您已经被踢出直播间，无法收到聊天及礼物消息，" +
                                        "需要杀掉进程重新登录");
                                adapter.notifyDataSetChanged();
                                LogFileUtil.getDefault().put(TAG, String.format("nim kickout  "));
                                break;
                        }
                    }
                }, true);
    }

    //初始化聊天室
    public void initChatRoom() {
        chatRoomGetOutListener();
        registerObservers(true);
        adapter.notifyDataSetChanged();
    }

    private void registerObservers(boolean register) {
        NIMClient.getService(ChatRoomServiceObserver.class).observeReceiveMessage(incomingChatRoomMsg, register);
    }

    //接收消息
    Observer<List<ChatRoomMessage>> incomingChatRoomMsg = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            // 处理新收到的消息
            for (IMMessage message : messages) {
                MsgTypeEnum msgType = message.getMsgType();
                MsgAttachment attachment = message.getAttachment();
                if (attachment instanceof ChatRoomNotificationAttachment) {
                    ChatRoomNotificationAttachment notificationAttachment = (ChatRoomNotificationAttachment) attachment;
                    //判断进到直播间的用户有没有登录
                    NotificationType messgeType = notificationAttachment.getType();
                    if (messgeType == NotificationType.ChatRoomMemberIn || messgeType == NotificationType.ChatRoomManagerAdd || messgeType == NotificationType.ChatRoomMemberTempMuteAdd || messgeType == NotificationType.ChatRoomManagerRemove) {
                        receiveMessage(message);
                        memberChange(messgeType);
                    }
                    //} else if (attachment instanceof GifAttachment) {
//                    Gift gift = new Gift();
//                    GifAttachment giftAttachment = (GifAttachment) attachment;
//                    gift.setId(Integer.parseInt(giftAttachment.getGiftID()));
//                    gift.setNum(Integer.parseInt(giftAttachment.getGiftNum()));
//                    gift.setName(giftAttachment.getGiftName());
//                    gift.setUserId(giftAttachment.getSenderName());
//                    giftShowManager.addGift(gift);
                } else if (attachment instanceof ResultAttachment) {
                    ResultAttachment resultAttachment = (ResultAttachment) attachment;
                    updateResultView(resultAttachment);
                } else if (attachment instanceof BetRankAndNumAttachment) {
                    updateBetRankAndOnlineNUmView((BetRankAndNumAttachment) attachment);
                } else {
                    if (!(attachment instanceof RobotAttachment)) {
                        if (attachment instanceof WinAttachment) {
                            if (((WinAttachment) attachment).getAnchorNickName()
                                    .equals(Application.getUser()
                                            .getExt_info().getNickname())) {
                                receiveMessage(message);
                            }
                        } else {
                            receiveMessage(message);
                        }
                    }
                }
            }
        }
    };

    private void memberChange(NotificationType messgeType) {
        if (messgeType == NotificationType.ChatRoomMemberIn || messgeType == NotificationType.ChatRoomMemberExit) {
            NIMClient.getService(ChatRoomService.class)
                    .fetchRoomInfo(roomId).setCallback(new RequestCallback<ChatRoomInfo>() {
                @Override
                public void onSuccess(ChatRoomInfo param) {
                    tvOnlineNum.setText(param.getOnlineUserCount() + "");
                }

                @Override
                public void onFailed(int code) {

                }

                @Override
                public void onException(Throwable exception) {

                }
            });
        }
    }

    //处理押注排行和更新直播间人数
    private void updateBetRankAndOnlineNUmView(BetRankAndNumAttachment attachment) {
        if (attachment.getAnchorStatus() != 0) {
            List<BetRank> newRanks = attachment.getRanks();
            ranks.clear();
            if (newRanks != null) {
                ranks.addAll(newRanks);
            }
            betOnRankAdapter.notifyDataSetChanged();
            int onlineNum = attachment.getOnlineNum();
            tvOnlineNum.setText(onlineNum + "");
            if (attachment.getAnchorStatus() == 2) {
                //:TODO 退出
                showToast(R.string.liveroom_error);
                NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
                finish();
                AppManager.getAppManager().finishActivity();
            }
        }
    }

    //处理结果
    private void updateResultView(ResultAttachment resultAttachment) {
        int gameStatus = resultAttachment.getGameStatus();
        if (resultAttachment.getAnchorStatus() == 2) {
            //:TODO 退出
            showToast(R.string.liveroom_error);
            NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
            //  finish();
            AppManager.getAppManager().finishActivity();
            return;
        }
        if (gameType.equals(resultAttachment.getGameType() + "")) {
            //--游戏类型1德州扑克2牛牛3龙虎4百家乐5老虎机
            if (gameType.equals("1")) {
                setDeZhouViews(resultAttachment);
            } else if (gameType.equals("2")) {
                setDeZhouViews(resultAttachment);
            } else if (gameType.equals("3")) {
                setLongHuChuViews(resultAttachment);
            } else if (gameType.equals("4")) {
                setBaiJiaLeViews(resultAttachment);
            } else if (gameType.equals("5")) {

            }
        }
        ;
    }

    //处理德州的结果控件或牛牛的结果
    private void setDeZhouViews(ResultAttachment resultAttachment) {
        int gameStatus = resultAttachment.getGameStatus();
        if (gameStatus == 1) {
            tvFuSuitPatterns.setText("- -");
            tvLuSuitPatterns.setText("- -");
            tvShouSuitPatterns.setText("- -");
            tvZhuangSuitPatterns.setText("- -");
            ivFuResult.setImageDrawable(null);
            ivLuResult.setImageDrawable(null);
            ivShouResult.setImageDrawable(null);
            showToast(getResources().getString(R.string.waitforbetting));
        } else if (gameStatus == 2) {
            tvFuSuitPatterns.setText("- -");
            tvLuSuitPatterns.setText("- -");
            tvShouSuitPatterns.setText("- -");
            tvZhuangSuitPatterns.setText("- -");
            ivFuResult.setImageDrawable(null);
            ivLuResult.setImageDrawable(null);
            ivShouResult.setImageDrawable(null);
            showToast(getResources().getString(R.string.wait_for_result));
        } else if (gameStatus == 3) {
            List<GamblingPartyResult> list = resultAttachment.getList();
            GamblingPartyResult zhuang = list.get(0);
            GamblingPartyResult fu = list.get(1);
            GamblingPartyResult lu = list.get(2);
            GamblingPartyResult shou = list.get(3);
            String zhuangCardTypeDec = zhuang.getCardTypeDec();
            String fuCardTypeDec = fu.getCardTypeDec();
            String luCardTypeDec = lu.getCardTypeDec();
            String shouCardTypeDec = shou.getCardTypeDec();
            tvZhuangSuitPatterns.setText(zhuangCardTypeDec);
            tvFuSuitPatterns.setText(fuCardTypeDec);
            tvLuSuitPatterns.setText(luCardTypeDec);
            tvShouSuitPatterns.setText(shouCardTypeDec);
            int zhuangGameResult = zhuang.getGame_result();
            int fuGameResult = fu.getGame_result();
            int luGameResult = lu.getGame_result();
            int shouGameResult = shou.getGame_result();

            if (fuGameResult == 0) {
                ivFuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.fushu));
            } else if (fuGameResult == 1) {
                ivFuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.fuying));
            } else if (fuGameResult == 2) {
                ivFuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.result_he2));
            }
            if (luGameResult == 0) {
                ivLuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.lushu));
            } else if (luGameResult == 1) {
                ivLuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.luying));
            } else if (luGameResult == 2) {
                ivLuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.result_he2));
            }
            if (shouGameResult == 0) {
                ivShouResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shoushu));
            } else if (shouGameResult == 1) {
                ivShouResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shouying));
            } else if (shouGameResult == 2) {
                ivShouResult.setImageDrawable(context.getResources().getDrawable(R.drawable.result_he2));
            }
        }
    }

    //处理龙虎
    private void setLongHuChuViews(ResultAttachment resultAttachment) {
        int gameStatus = resultAttachment.getGameStatus();
        if (gameStatus == 1) {
            tvLongResult.setText("- -");
            tvLongResult.setVisibility(View.VISIBLE);
            ivLongResult.setVisibility(View.GONE);
            tvHeResult.setText("- -");
            tvHeResult.setVisibility(View.VISIBLE);
            ivHeResult.setVisibility(View.GONE);
            tvHuResult.setText("- -");
            tvHuResult.setVisibility(View.VISIBLE);
            ivHuResult.setVisibility(View.GONE);
            showToast(getResources().getString(R.string.waitforbetting));
        } else if (gameStatus == 2) {
            tvLongResult.setText("- -");
            tvLongResult.setVisibility(View.VISIBLE);
            ivLongResult.setVisibility(View.GONE);
            tvHeResult.setText("- -");
            tvHeResult.setVisibility(View.VISIBLE);
            ivHeResult.setVisibility(View.GONE);
            tvHuResult.setText("- -");
            tvHuResult.setVisibility(View.VISIBLE);
            ivHuResult.setVisibility(View.GONE);
            showToast(getResources().getString(R.string.wait_for_result));
        } else if (gameStatus == 3) {
            tvLongResult.setVisibility(View.GONE);
            tvHeResult.setVisibility(View.GONE);
            tvHuResult.setVisibility(View.GONE);
            ivLongResult.setVisibility(View.VISIBLE);
            ivHeResult.setVisibility(View.VISIBLE);
            ivHuResult.setVisibility(View.VISIBLE);
            List<GamblingPartyResult> list = resultAttachment.getList();
            GamblingPartyResult Long = list.get(0);
            GamblingPartyResult He = list.get(1);
            GamblingPartyResult Hu = list.get(2);
            String longCardTypeDec = Long.getCardTypeDec();
            String heCardTypeDec = He.getCardTypeDec();
            String huCardTypeDec = Hu.getCardTypeDec();
            tvLongResult.setText(longCardTypeDec);
            tvHeResult.setText(heCardTypeDec);
            tvHuResult.setText(huCardTypeDec);
            int longGameResult = Long.getGame_result();
            int heGameResult = He.getGame_result();
            int huGameResult = Hu.getGame_result();

            if (longGameResult == 0) {
                ivLongResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (longGameResult == 1) {
                ivLongResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (heGameResult == 0) {
                ivHeResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (heGameResult == 1) {
                ivHeResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (huGameResult == 0) {
                ivHuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (huGameResult == 1) {
                ivHuResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
        }
    }

    //处理百家乐
    private void setBaiJiaLeViews(ResultAttachment resultAttachment) {
        int gameStatus = resultAttachment.getGameStatus();
        if (gameStatus == 1) {
            tvBJLZhuangDuiResult.setText("- -");
            tvBJLZhuangResult.setText("- -");
            tvBJLHeResult.setText("- -");
            tvBJLXianResult.setText("- -");
            tvBJLXianDuiResult.setText("- -");
            tvBJLZhuangDuiResult.setVisibility(View.VISIBLE);
            tvBJLZhuangResult.setVisibility(View.VISIBLE);
            tvBJLHeResult.setVisibility(View.VISIBLE);
            tvBJLXianResult.setVisibility(View.VISIBLE);
            tvBJLXianDuiResult.setVisibility(View.VISIBLE);

            ivBJLZhuangDuiResult.setVisibility(View.GONE);
            ivBJLZhuangResult.setVisibility(View.GONE);
            ivBJLHeResult.setVisibility(View.GONE);
            ivBJLXianResult.setVisibility(View.GONE);
            ivBJLXianDuiResult.setVisibility(View.GONE);
            showToast(getResources().getString(R.string.waitforbetting));
        } else if (gameStatus == 2) {
            tvBJLZhuangDuiResult.setText("- -");
            tvBJLZhuangResult.setText("- -");
            tvBJLHeResult.setText("- -");
            tvBJLXianResult.setText("- -");
            tvBJLXianDuiResult.setText("- -");
            tvBJLZhuangDuiResult.setVisibility(View.VISIBLE);
            tvBJLZhuangResult.setVisibility(View.VISIBLE);
            tvBJLHeResult.setVisibility(View.VISIBLE);
            tvBJLXianResult.setVisibility(View.VISIBLE);
            tvBJLXianDuiResult.setVisibility(View.VISIBLE);

            ivBJLZhuangDuiResult.setVisibility(View.GONE);
            ivBJLZhuangResult.setVisibility(View.GONE);
            ivBJLHeResult.setVisibility(View.GONE);
            ivBJLXianResult.setVisibility(View.GONE);
            ivBJLXianDuiResult.setVisibility(View.GONE);
            showToast(getResources().getString(R.string.wait_for_result));
        } else if (gameStatus == 3) {
            tvBJLZhuangDuiResult.setVisibility(View.GONE);
            tvBJLZhuangResult.setVisibility(View.GONE);
            tvBJLHeResult.setVisibility(View.GONE);
            tvBJLXianResult.setVisibility(View.GONE);
            tvBJLXianDuiResult.setVisibility(View.GONE);

            ivBJLZhuangDuiResult.setVisibility(View.VISIBLE);
            ivBJLZhuangResult.setVisibility(View.VISIBLE);
            ivBJLHeResult.setVisibility(View.VISIBLE);
            ivBJLXianResult.setVisibility(View.VISIBLE);
            ivBJLXianDuiResult.setVisibility(View.VISIBLE);
            List<GamblingPartyResult> list = resultAttachment.getList();
            GamblingPartyResult zhuang = list.get(0);
            GamblingPartyResult he = list.get(1);
            GamblingPartyResult xian = list.get(2);
            GamblingPartyResult zhuangDui = list.get(3);
            GamblingPartyResult xianDui = list.get(4);
            String zhuangCardTypeDec = zhuang.getCardTypeDec();
            String heCardTypeDec = he.getCardTypeDec();
            String xianCardTypeDec = xian.getCardTypeDec();
            String zhuangDuiCardTypeDec = zhuangDui.getCardTypeDec();
            String xianDuiCardTypeDec = xianDui.getCardTypeDec();
            tvBJLZhuangResult.setText(zhuangCardTypeDec);
            tvBJLHeResult.setText(heCardTypeDec);
            tvBJLXianResult.setText(xianCardTypeDec);
            tvBJLZhuangDuiResult.setText(zhuangDuiCardTypeDec);
            tvBJLXianDuiResult.setText(xianDuiCardTypeDec);
            int zhuangGameResult = zhuang.getGame_result();
            int heGameResult = he.getGame_result();
            int xianGameResult = xian.getGame_result();
            int zhuangDuiGameResult = zhuangDui.getGame_result();
            int xianDuiGameResult = xianDui.getGame_result();


            if (zhuangGameResult == 0) {
                ivBJLZhuangResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (zhuangGameResult == 1) {
                ivBJLZhuangResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (heGameResult == 0) {
                ivBJLHeResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (heGameResult == 1) {
                ivHeResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (xianGameResult == 0) {
                ivBJLXianResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (xianGameResult == 1) {
                ivBJLXianResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (zhuangDuiGameResult == 0) {
                ivBJLZhuangDuiResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (zhuangDuiGameResult == 1) {
                ivBJLZhuangDuiResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
            if (xianDuiGameResult == 0) {
                ivBJLXianDuiResult.setImageDrawable(context.getResources().getDrawable(R.drawable.shu));
            } else if (xianDuiGameResult == 1) {
                ivBJLXianDuiResult.setImageDrawable(context.getResources().getDrawable(R.drawable.ying));
            }
        }
    }

    //发送普通消息
    public void sendMessage(String comment) {
        if (!TextUtils.isEmpty(comment)) {
            final ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(roomId, comment);
            NIMClient.getService(ChatRoomService.class).sendMessage(message, false).setCallback(new RequestCallback<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    chatRoomMessages.add(message);
                    adapter.notifyDataSetChanged();
                    ListViewUtil.scrollToBottom(lvComment);
                }

                @Override
                public void onFailed(int i) {
                    if (i == 13004) {
                        showToast("您已被禁言");
                    } else {
                        showToast(i + "");
                    }
                }

                @Override
                public void onException(Throwable throwable) {
                    showToast("错误");
                }
            });
        }
    }

    private void receiveMessage(IMMessage message) {
        if (isGift(message)) {
            reciveGift(message);
        }
        chatRoomMessages.add(message);
        adapter.notifyDataSetChanged();
        ListViewUtil.scrollToBottom(lvComment);
    }

    private void reciveGift(IMMessage message) {

        MsgAttachment attachment = message.getAttachment();
        GifAttachment giftAttachment = (GifAttachment) attachment;
        /*if (giftAttachment.getGiftID().equals("39") ||
                giftAttachment.getGiftID().equals("40") ||
                giftAttachment.getGiftID().equals("41") ||
                giftAttachment.getGiftID().equals("42") ||
                giftAttachment.getGiftID().equals("43") ||
                giftAttachment.getGiftID().equals("44") ||
                giftAttachment.getGiftID().equals("45") ||
                giftAttachment.getGiftID().equals("46")) {
           *//* Gift gift = new Gift();
            gift.setName(giftAttachment.getGiftName());
            gift.setUserId(giftAttachment.getSenderName());
            gift.setNum(Integer.parseInt(giftAttachment.getGiftNum()));
            gift.setNoFrameIcon(giftAttachment.getGiftShowImage());
            gift.setId(Integer.parseInt(giftAttachment.getGiftID()));
            queue.add(gift);*//*
            for (int i = 0; i < giftAttachment.getGiftNum(); i++) {
                tietuGift.add(giftAttachment);
            }
            if (tietuGift.size() == giftAttachment.getGiftNum()
                    && selectedFace.equals("none")
                    ) {
                giftHandler.removeCallbacksAndMessages(null);
                giftHandler.sendEmptyMessage(0);
            }
            *//*ZegoApiManager.getInstance().getFaceunityController().
                    onEffectItemSelected(EffectAndFilterSelectAdapter.EFFECTNAMEMAP
            .get(giftAttachment.getGiftID()));*//*
        } else {
            Gift gift = new Gift();
            gift.setName(giftAttachment.getGiftName());
            gift.setUserId(giftAttachment.getSenderName());
            gift.setNum(giftAttachment.getGiftNum());
            gift.setNoFrameIcon(giftAttachment.getGiftShowImage());
            giftShowManager.addGift(gift);
            giftShowManager.showGift();
        }*/

        Gift gift = new Gift();
        gift.setName(giftAttachment.getGiftName());
        gift.setUserId(giftAttachment.getSenderName());
        gift.setNum(giftAttachment.getGiftNum());
        gift.setNoFrameIcon(giftAttachment.getGiftShowImage());
        giftShowManager.addGift(gift);
        giftShowManager.showGift();


        int isNeedNoticeAnchor = giftAttachment.getIsNeedNoticeAnchor();
        //0不需要1需要
        if (isNeedNoticeAnchor == 1) {
            //mVibrator.vibrate(new long[]{1000, 500, 0, 0}, -1);
        }
        //      mVibrator.vibrate(new long[]{1000, 500, 0, 0}, -1);
    }

    private boolean isGift(IMMessage message) {
        MsgAttachment attachment = message.getAttachment();
        if (attachment instanceof GifAttachment) {
            return true;
        } else {
            return false;
        }
    }

    //监听被踢出聊天室
    private void chatRoomGetOutListener() {
        NIMClient.getService(ChatRoomServiceObserver.class)
                .observeKickOutEvent(kickOutObserver, false);
    }

    Observer<ChatRoomKickOutEvent> kickOutObserver = new Observer<ChatRoomKickOutEvent>() {
        @Override
        public void onEvent(ChatRoomKickOutEvent chatRoomKickOutEvent) {
            // 提示被踢出的原因（聊天室已解散、被管理员踢出、被其他端踢出等）
            // 清空缓存数据
            chatRoomMessages.add("系统消息：您的账号在别处登录，您已经被踢出直播间，无法收到聊天及礼物消息，" +
                    "需要杀掉进程重新登录");
            adapter.notifyDataSetChanged();
            LogFileUtil.getDefault().put(TAG, String.format("nim kickout , someone login with this account on another device "));
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        prepareLive();
//        if (mMediaStreamingManager != null) {
//            mMediaStreamingManager.resume();
//        }
//        svCamera.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // You must invoke pause here.
//        mMediaStreamingManager.pause();
//        faceunity.fuOnDeviceLost();
//        mFuNotifyPause = true;
//        m_frame_id = 0;
    }


    @OnClick({R.id.btnCameraTurn, R.id.rlAnchorInfo, R.id.btnGiftRank, R.id.ivClose, R.id.llBetonRank, R.id.llGiftHistory})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCameraTurn:
                if (fontCam) {
                    mZegoLiveRoom.setFrontCam(false);

                    fontCam = false;
                } else {
                    mZegoLiveRoom.setFrontCam(true);
                    fontCam = true;
                }
                break;
            case R.id.rlAnchorInfo:
                //       llEditAnchorInfo.setVisibility(View.VISIBLE);
                Intent intent = new Intent();
                intent.setClass(context, EditAnchorInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.btnGiftRank:
                //    sendGiftA();
                //     sendMessage("我是你爸爸你爸爸爸爸");
                //   toGiftContributionActivity();
                loadGiftNumRanking();
                break;
            case R.id.ivClose:
                sureCloseDialog();
                break;
            case R.id.llBetonRank:
                if (lvBetonRank.getVisibility() == View.VISIBLE) {
                    lvBetonRank.setVisibility(View.GONE);
                } else {
                    lvBetonRank.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.llGiftHistory:
                loadTodayGiftRecord();
                break;
        }
    }

    private void loadTodayGiftRecord() {
        User user = Application.getUser();
        presenter.loadTodayGiftRecord(user.getUser_code());
    }

    private void toGiftContributionActivity() {
        Intent intent = new Intent();
        intent.setClass(context, GiftContributionActivity.class);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
//        if (llEditAnchorInfo.getVisibility() == View.VISIBLE) {
//            llEditAnchorInfo.setVisibility(View.GONE);
//        } else {
//        super.onBackPressed();
//        }
        sureCloseDialog();
    }

    private void createTodayGiftRankDialog(List<ReceiveGift> list) {
        View view = View.inflate(context, R.layout.layout_todaygiftrank_dialog, null);

        ListView lvTodayGiftRank = (ListView) view.findViewById(R.id.lvTodayGiftRank);
        TodayGiftRankAdapter todayGiftRankAdapter = new TodayGiftRankAdapter(context, list);
        lvTodayGiftRank.setAdapter(todayGiftRankAdapter);
        final Dialog dialog = new Dialog(context, R.style.Theme_Transparent);
        dialog.setContentView(view);
        dialog.show();
        view.findViewById(R.id.btnSure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void sureCloseDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(exitEdit);
        dialog.setListener(() -> {
            anchorOff();
            release();
            liveClosed = true;
            NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
            LogUtil.e(TAG, "Bitmap " + System.currentTimeMillis());
            Bitmap bitmap = textureView.getBitmap(DeviceUtils.dp2px(context, 360 / 3),
                    DeviceUtils.dp2px(context, 640 / 3));
            Intent intent = new Intent(LiveRoomActivity.this, LiveEndActivity.class);
            LiveHelper.bitmap = bitmap;

            LogFileUtil.getDefault().put(TAG, String.format("click exit button , exit liveroom and to LiveEndActivity"));

            intent.putExtra("starttime", startTime);
            AppManager.getAppManager().finishActivity();
            startActivity(intent);
            finish();
        });
        dialog.show();
    }


    @Override
    public void commentHandle(String userId) {
        queryChatRoomUser(userId);
    }

    private void createCommnetClickDialog(ChatRoomMember member, final String userId) {
        View view = View.inflate(context, R.layout.layout_chatroomhandle_dialog, null);
        ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
        TextView tvShutUp = (TextView) view.findViewById(R.id.tvShutUp);
        TextView tvSetAdmin = (TextView) view.findViewById(R.id.tvSetAdmin);
        ImageView ivHeader = (ImageView) view.findViewById(R.id.ivHeader);
        TextView tvUserName = (TextView) view.findViewById(R.id.tvUserName);
        commentDialog = new Dialog(context, R.style.Theme_Transparent);
        commentDialog.setContentView(view);
        commentDialog.show();
        String avatar = member.getAvatar();
        String nickName = member.getNick();
        int memberType = member.getMemberType().getValue();
        if (memberType == MemberType.ADMIN.getValue()) {
            tvSetAdmin.setText(R.string.remove_admin);
            tvSetAdmin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setAdmin(userId);
                }
            });
        } else if (memberType == MemberType.GUEST.getValue() || memberType == MemberType.LIMITED.getValue() || memberType == MemberType.NORMAL.getValue()) {
            tvSetAdmin.setText(R.string.set_admin);
            tvSetAdmin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setAdmin(userId);
                }
            });
        } else if (memberType == MemberType.CREATOR.getValue()) {
            tvSetAdmin.setText(R.string.anchor);
        } else {
            tvSetAdmin.setText(R.string.unknow);
        }
        if (memberType != MemberType.ADMIN.getValue()) {
            tvShutUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shutUp(userId);
                }
            });
        }
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentDialog.dismiss();
            }
        });
        AsyncImage.loadPhoto(context, avatar, ivHeader);
        if (TextUtils.isEmpty(nickName)) {
            tvUserName.setText("");
        } else {
            tvUserName.setText(nickName);
        }
    }

    private void setAdmin(String userId) {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("operator", user.getUser_code());
        params.put("roomid", roomId);
        params.put("user_code", userId);
        presenter.setChatroomAdmin(params);
    }

    private void shutUp(String userId) {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("operator", user.getUser_code());
        params.put("roomid", roomId);
        params.put("target", userId);
        params.put("muteDuration", 86400 + "");
        presenter.chatroomMute(params);
    }

    //查询用户
    private void queryChatRoomUser(final String userId) {
        List<String> accounts = new ArrayList<>();
        accounts.add(userId);
        NIMClient.getService(ChatRoomService.class).fetchRoomMembersByIds(roomId, accounts).setCallback(new RequestCallback() {

            @Override
            public void onSuccess(Object o) {
                ArrayList<ChatRoomMember> memberList = (ArrayList) o;
                int size = memberList.size();
                if (size == 0) {
                    showToast(R.string.user_not_exist);
                } else {
                    createCommnetClickDialog(memberList.get(0), userId);
                }
            }

            @Override
            public void onFailed(int i) {
                showToast(i + "");
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        myHandler.removeCallbacksAndMessages(null);
//        giftHandler.removeCallbacksAndMessages(null);
        release();
        giftShowManager.release();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        unregisterReceiver(receiver);
        if (webSocket != null) {
            webSocket.removeListener();
        }
        LogUtil.e(TAG, "onDestroy " + String.valueOf(webSocket == null));
        LogFileUtil.getDefault().put(TAG, String.format("onDestroy "));
        super.onDestroy();
    }

    //主播上下线
    private void anchorOff() {

        String userStr = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(userStr, User.class);
        String id = user.getUser_code();
        int roomId = user.getAnchor().getRoom_id_pk();
        Map<String, Object> params = new HashMap<>();
        params.put("anchor_user_code", id);
        params.put("anchor_status", 0);
        params.put("game_type", "2");
        params.put("room_id_pk", roomId + "");
        presenter.anchorOnOff(params);
        LogFileUtil.getDefault().put(TAG, String.format("exit liveroom and call anchorOff() "));
        // 停止publish前，必须停止预览
        mZegoLiveRoom.stopPreview();
        mZegoLiveRoom.stopPublishing();
        mZegoLiveRoom.setPreviewView(null);


// 在离开直播或者观看页面时，请将sdk的callback置空，避免内存泄漏
// 清空回调, 避免内存泄漏
        mZegoLiveRoom.setZegoLivePublisherCallback(null);
        mZegoLiveRoom.setZegoLivePlayerCallback(null);
        mZegoLiveRoom.setZegoRoomCallback(null);


// 退出房间
        mZegoLiveRoom.logoutRoom();


    }

    private void selectTietu() {
        GifAttachment gift = tietuGift.poll();
        ZegoApiManager.getInstance().getFaceunityController().
                onEffectItemSelected(EffectAndFilterSelectAdapter.EFFECTNAMEMAP
                        .get(gift.getGiftID()));
        selectedFace = EffectAndFilterSelectAdapter.EFFECTNAMEMAP
                .get(gift.getGiftID());
    }


    private void loadGiftNumRanking() {
        String strUser = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(strUser, User.class);
        presenter.getGiftRank(user.getUser_code());
        isRanking = false;
    }

    private void createGiftNumDialog() {

        View view = View.inflate(context, R.layout.layout_gifrank_dialog, null);
        Dialog dialog = new Dialog(context, R.style.Theme_Transparent);
        //     final AlertDialog dialog = new AlertDialog.Builder(this).create();
        ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
        TextView tvToady = (TextView) view.findViewById(R.id.tvToday);
        TextView tvWeek = (TextView) view.findViewById(R.id.tvWeek);
        TextView tvMonth = (TextView) view.findViewById(R.id.tvMonth);
        ListView lvGiftNum = (ListView) view.findViewById(R.id.lvGiftNum);
        //   TextView tvTotal = (TextView) view.findViewById(R.id.tvTotal);
        receiveGiftRankAdapter = new ReceiveGiftRankAdapter(context, receiveGiftlist);
        lvGiftNum.setAdapter(receiveGiftRankAdapter);
        setDialogItemSelected(tvToady, tvWeek, tvMonth, 1);
        MyDialogClickListener listener = new MyDialogClickListener(dialog, ivClose, tvToady, tvWeek, tvMonth);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        tvToady.setOnClickListener(listener);
        tvWeek.setOnClickListener(listener);
        tvMonth.setOnClickListener(listener);
        ivClose.setOnClickListener(listener);
        dialog.show();
    }

    @Override
    public void setPresenter(LiveRoomContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showMuteResult(BaseData data) {
        commentDialog.dismiss();
        if (data.getCode() == 1) {
            showToast(R.string.mute_success);
        } else {
            showToast(R.string.mute_failed);
        }
    }

    @Override
    public void showSetAdminResult(BaseData data) {
        commentDialog.dismiss();
        LinkedTreeMap<String, Object> result = (LinkedTreeMap<String, Object>) data.getData();
        if (data.getCode() == 1) {
            if ((double) result.get("operation") == 1.0) {
                showToast(R.string.set_admin_success);
            } else {
                showToast(R.string.remove_admin_success);
            }
        } else {
            if ((double) result.get("operation") == 1.0) {
                showToast(R.string.set_admin_failed);
            } else {
                showToast(R.string.remove_admin_failed);
            }
        }
    }

    @Override
    public void showGiftRecord(BaseData<List<ReceiveGift>> data) {
        createTodayGiftRankDialog(data.getData());
    }

    @Override
    public void showGiftRanking(BaseData<GiftRankingData> data) {
        total = data.getData().getTotal();
        week = data.getData().getWeek();
        month = data.getData().getMonth();
        if (!isRanking) {
            createGiftNumDialog();
        }
    }

    @Override
    public void showAnchorDetail(AnchorInfo anchorInfo) {
        if (anchorInfo.getAnchor_status() != 1) {  //非在线状态
            anchorOn();
        }
        myHandler.sendEmptyMessageDelayed(CODE_QUERYSTATUS, 5 * 60 * 1000);
    }

    @Override
    public void showGameData(Game data, int status) {
        if (status == 1) {
            gameType = data.getGame_type() != null ? data.getGame_type() : gameType;
            initGameZone();
        }
    }


    private void anchorOn() {
        String userStr = PreferenceUtils.getString(PreferenceUtils.USER);
        User user = new Gson().fromJson(userStr, User.class);
        String id = user.getUser_code();
        int roomId = user.getAnchor().getRoom_id_pk();
        Map<String, Object> params = new HashMap<>();
        params.put("anchor_user_code", id);
        params.put("anchor_status", 1);
        params.put("game_type", "2");
        params.put("room_id_pk", roomId + "");
        presenter.anchorOnOff(params);
    }


    int index = 0;


    private class MyDialogClickListener implements View.OnClickListener {
        Dialog dialog;
        TextView tvToday;
        TextView tvWeek;
        TextView tvMonth;
        ImageView ivClose;
        //     TextView tvTotal;

        MyDialogClickListener(Dialog dialog, ImageView ivClose, TextView tvToday, TextView tvWeek, TextView tvMonth) {
            this.dialog = dialog;
            this.tvToday = tvToday;
            this.tvWeek = tvWeek;
            this.tvMonth = tvMonth;
            this.ivClose = ivClose;
            //       this.tvTotal = tvTotal;
        }


        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.ivClose) {
                dialog.dismiss();
            } else if (v.getId() == R.id.tvToday) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth, 0);

            } else if (v.getId() == R.id.tvWeek) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth, 1);

            } else if (v.getId() == R.id.tvMonth) {
                setDialogItemSelected(tvToday, tvWeek, tvMonth,
                        2);
            }
        }
    }

    private void setDialogItemSelected(TextView tvToday, TextView tvWeek, TextView tvMonth, int position) {
        switch (position) {
            case 0:
                tvToday.setBackground(getResources().getDrawable(R.drawable.shape_giftlefttitle_bg));
                tvToday.setTextColor(getResources().getColor(R.color.black));
                tvWeek.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setBackground(null);
                tvMonth.setTextColor(getResources().getColor(R.color.white));
                tvMonth.setBackground(null);
                receiveGiftlist.clear();
                receiveGiftlist.addAll(week);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
            case 1:
                tvToday.setBackground(null);
                tvToday.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setTextColor(getResources().getColor(R.color.black));
                tvWeek.setBackgroundColor(getResources().getColor(R.color.white));
                tvMonth.setTextColor(getResources().getColor(R.color.white));
                tvMonth.setBackground(null);
                receiveGiftlist.clear();
                receiveGiftlist.addAll(month);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
            case 2:
                tvToday.setBackground(null);
                tvToday.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setTextColor(getResources().getColor(R.color.white));
                tvWeek.setBackground(null);
                tvMonth.setTextColor(getResources().getColor(R.color.black));
                tvMonth.setBackground(getResources().getDrawable(R.drawable.shape_giftrighttitle_bg));
                receiveGiftlist.clear();
                receiveGiftlist.addAll(day);
                receiveGiftRankAdapter.notifyDataSetChanged();
                break;
        }
    }

    private class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
            Log.e("NetBroadcastReceiver", "onReceive");
            if (intent.getAction().equals(NET_CHANGE_ACTION)) {
                int netWorkState = NetUtil.getNetworkState(context);
                Log.e("NetBroadcastReceiver", "onReceive" + netWorkState);
                // 接口回调传过去状态的类型
                onNetChange(netWorkState);
            }
        }
    }

    private void onNetChange(int netWorkState) {
        if (isNetConnect(netWorkState) && needRepaire) {
            needRepaire = false;
            prepareLive();
        }
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect(int code) {
        if (code == 1) {
            return true;
        } else if (code == 2) {
            return true;
        } else if (code == 0) {
            return false;
        }
        return false;
    }

    private void connectWebSocket() {
        if (liveClosed) {
            return;
        }
        if (webSocket != null) {
            release();
        }
        L.e(TAG, " onConnect connectWebSocket");
        User user = Application.getUser();
        StringBuilder url = new StringBuilder(API.WS_HOST)
                .append(API.LONG_URL)
                .append("userCode=")
                .append(user.getUser_code())
                .append("&anchor_user_code=")
                .append(user.getUser_code())
                .append("&game_type=")
                .append(gameType)
                .append("&device=2")
                /*.append("&token=" + user.getToken())*/;

        webSocket = LiveWebSocket.getDefault(new LiveWebSocket.Callback() {
            @Override
            public void onOpen(WebSocket socket, Response response) {
                L.e(TAG, " onConnect onOpen");
                recoonCount = 0;
                myHandler.removeMessages(CODE_QUERYSTATUS);
                myHandler.sendEmptyMessageDelayed(CODE_QUERYSTATUS, 5 * 60 * 1000);
                myHandler.sendEmptyMessage(CODE_SENDHEARTBEAT);

                LogFileUtil.getDefault().put(TAG, String.format("socket connect open  "));
            }

            @Override
            public void onReceive(LgMessage message) {

            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                myHandler.removeMessages(CODE_SENDHEARTBEAT);
//                myHandler.removeMessages(CODE_RECONNECT);
//                myHandler.sendEmptyMessage(CODE_RECONNECT);
                L.e(TAG, " onConnect onClosed");
                LogFileUtil.getDefault().put(TAG, String.format("socket onClosed  "));
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                myHandler.removeMessages(CODE_SENDHEARTBEAT);
                myHandler.removeMessages(CODE_RECONNECT);
                myHandler.sendEmptyMessageDelayed(CODE_RECONNECT, 30 * 1000);
                L.e(TAG, " onConnect onFailure");
                LogFileUtil.getDefault().put(TAG, String.format("socket connect onFailure  "));
            }
        });

        client = new OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        request = new Request.Builder().url(url.toString()).get().build();
        client.newWebSocket(request, webSocket);
        client.dispatcher().executorService().shutdown();
    }

    private void release() {
        LogUtil.e(TAG, "exectime release  " + System.currentTimeMillis());
        if (webSocket != null)
            webSocket.closeWebSocket();
        client = null;
        request = null;
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    private void showExitDialog(String title) {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(() -> {
            finish();
            release();
            anchorOff();
        });
        dialog.setTitle(title);
        dialog.setSingleButton();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    CommonDialog badNetDialog;

    private void showBadNetWorkDialog() {
        if (badNetDialog == null) {
            badNetDialog = new CommonDialog(this);
        }
        if (badNetDialog.isShowing()) return;
        badNetDialog.setTitle("当前网络环境较差，\n可能影响直播效果");
        badNetDialog.setSingleButton();
        badNetDialog.setCancelable(false);
        badNetDialog.setCanceledOnTouchOutside(false);
        badNetDialog.show();
        badNetDialog.setListener(() -> badNetwork = 0);
        LogFileUtil.getDefault().put(TAG, String.format(" bad network exception "));
    }


    private void getAnchorDetail() {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("anchor_user_code", user.getUser_code());
        params.put("currency", "CNY");
        presenter.getAnchorDetail(params);
    }
}
